package com.miracle.test;

public class 移位和与或运算 {
    public static void main(String[] args) {
        // 移位和无符号移位运算();
        位或运算();
    }

    public static void 移位和无符号移位运算(){
        int num = 10;
        printBinary(num);

        int num2 = num << 1; //二进制左移一位 -> num*2
        printBinary(num2);

        int num3 = num >> 1; //二进制右移一位 -> num/2
        printBinary(num3);

        //========================================
        int fNum = 10;
        printBinary(fNum);

         fNum |= fNum >>> 1;//通过移位和位与运算之后，最终得到大于该数的2的n次幂减1（因为二进制数的所有位都变为1）
         fNum |= fNum >>> 2;
         fNum |= fNum >>> 4;
         fNum |= fNum >>> 8;
         fNum |= fNum >>> 16;
        printBinary(fNum);
        System.out.println(fNum);
    }

    public static void 位或运算(){
        int a = 100;
        printBinary(a);

        a |= a>>1;
        printBinary(a);

        a |= a>>1;
        printBinary(a);
    }

    public static void printBinary(int num){
        System.out.println(num + " -> " + Integer.toBinaryString(num));
    }
}
